package org.jcms.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jcms.model.Customer;
import org.jcms.model.Order;
import org.jcms.model.State;
import org.jcms.service.OrderServiceI;
import org.jcms.service.StateServiceI;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 取消订单：参数名 orderId
 * 
 * @author Administrator
 * 
 */
public class CustomerCancelOrder extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public CustomerCancelOrder() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ApplicationContext ac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		OrderServiceI orderServiceI = (OrderServiceI) ac
				.getBean("orderServiceImpl");
		StateServiceI stateServiceI = (StateServiceI) ac
				.getBean("stateServiceImpl");
		String retJson = "{\"error\":@err,\"msg\":\"@msg\"}";
		String err = "1";
		String msg = "";
		String orderId = request.getParameter("orderId");
		Customer customer = (Customer) request.getSession().getAttribute(
				"customer");

		try {

			if (orderId == null || "".equals(orderId)) {
				msg = "订单ID不能为空";
				return;
			}

			Order order = orderServiceI.findById(orderId);
			if (order == null) {
				msg = "要取消的订单不存在";
				return;
			}

			if (customer == null
					|| !customer.getCustomerId().equals(
							order.getCustomer().getCustomerId())) {

				msg = "不能取消不属于自己的订单";
				return;
			}

			int orderStateID = order.getState().getStateId();
			if (orderStateID != 0) {

				msg = "只能取消还未被审核的订单";
				return;
			}

			State state = stateServiceI.findById(5);
			order.setState(state);
			orderServiceI.update(order);
			err = "0";
			msg = "订单(" + orderId + ")成功取消";

		} catch (Exception e) {
			msg = "系统出错";
		} finally {
			retJson = retJson.replace("@err", err);
			retJson = retJson.replace("@msg", msg);
			response.getOutputStream().write(retJson.getBytes("utf-8"));
		}
	}

	public void init() throws ServletException {

	}

}
